// 统一的消息发送工具
class MessagingManager {
    // 发送到 Background
    async sendToBackground(action: string, data?: any) {
      try {
        return await chrome.runtime.sendMessage({
          action,
          data,
          timestamp: new Date().toISOString(),
          source: "popup" // 或 "content"
        })
      } catch (error) {
        console.error(`发送消息到 Background 失败: ${action}`, error)
        throw error
      }
    }
  
    // 发送到 Content Script
    async sendToContentScript(tabId: number, action: string, data?: any) {
      try {
        return await chrome.tabs.sendMessage(tabId, {
          action,
          data,
          timestamp: new Date().toISOString(),
          source: "background" // 或 "popup"
        })
      } catch (error) {
        console.error(`发送消息到 Content Script 失败: ${action}`, error)
        throw error
      }
    }
  
    // 广播到所有 Content Scripts
    async broadcastToAllTabs(action: string, data?: any) {
      const tabs = await chrome.tabs.query({})
      const results = []
      
      for (const tab of tabs) {
        if (tab.id) {
          try {
            const result = await this.sendToContentScript(tab.id, action, data)
            results.push({ tabId: tab.id, success: true, result })
          } catch (error) {
            results.push({ tabId: tab.id, success: false, error })
          }
        }
      }
      
      return results
    }
  }
  
  export const messaging = new MessagingManager()